import {uSelectDevParamCheckData} from '@/api/deviceManagement'
import {selectSimpleDevList, selectSimpleDevListPageList} from '@/api/public'
import {CCard} from '@/components/card'
import {ProductFilesItem} from '@/components/others/productFilesItem'
import {
  CnBoldP,
  CnBoldSpan,
  CnMediumP,
  CnNormalP,
  CnNormalSpan,
  CnMediumSpan
} from '@/components/text'
import {ParamValue} from '@/components/text/paramValue'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {getUserId} from '@/libs/auth'
import {RouterView} from 'vue-router'
import {DeviceCard} from './components/deviceCard'
import {uSelectDevFunBydDevId, uSelectMyDevManagerData} from '@/api/deviceManagement'
import {UtilButtonLine} from '@/components/btn/utilBtn'
import {DeviceStatusOfStatus, IconImg, ParamOfIcon} from '@/components/image'
import {toDevInfo} from '@/libs/pageRedirect'
// import {CnBoldP, CnBoldSpan, CnMediumP, CnMediumSpan, CnNormalSpan} from '@/components/text'
import './index.less'

export default defineComponent({
  name: 'deviceManagement',
  setup() {
    const {store, route} = useGlobalAPI()
    const state = reactive<{
      dataSource: SimpleDeviceData[]
      spinning: boolean
      currentDev: SimpleDeviceData | undefined
      paramListUpdateFlag: boolean
      paramsData: DeviceManagement.CheckData[]
    }>({
      dataSource: [],
      spinning: false,
      currentDev: undefined,
      paramListUpdateFlag: false,
      paramsData: []
    })

    const paramDataTime = computed(() =>
      state.paramListUpdateFlag
        ? ''
        : state.paramsData.length && state.paramsData[0].checkTime
        ? '时间：' + state.paramsData[0].checkTime
        : '暂无日期'
    )

    const devByCurrentDevId = computed(
      () => state.dataSource.filter(item => item.devId === state.currentDev?.devId)[0]
    )

    function getPageDataSource() {
      state.spinning = true
      const userId = getUserId()
      // const
      const data = {
        page: current.value,
        size: size.value,
        platFormSubUserId: Number(userId),
        devName: searchFormData.name
      }
      if (!userId) return

      selectSimpleDevListPageList(data)
        .then(res => {
          console.log(res)
          devDataTableList.value = res.data.list
          total.value = res.data.total
          console.log(total.value)

          // state.dataSource = res.data.sort((a, b) => a.devId - b.devId)
          // state.spinning = false
          // state.currentDev = res.data[0]
          // getParamsDataByDevId(state.currentDev.devId)
          state.spinning = false
        })
        .catch(err => {
          state.spinning = false
        })
    }

    function getParamsDataByDevId(devId: number) {
      state.paramListUpdateFlag = true
      store.dispatch('layoutMain/MAINSCROLLTOTOP', 'deviceManagementParamDashboard')
      uSelectDevParamCheckData({devId})
        .then(res => {
          state.paramsData = res.data || []
          setTimeout(() => (state.paramListUpdateFlag = false), 500)
        })
        .catch(err => {
          state.paramListUpdateFlag = false
        })
    }

    onMounted(() => {
      getPageDataSource()
    })

    // 当前页
    const current = ref(1)
    // 每页N条
    const size = ref(10)

    // 总共多少条
    const total = ref(0)
    // 设备管理数据表格的数据
    const devDataTableList = ref<any>([])
    // 设备管理数据表格的表格字段规则
    const devDataTableColumns = ref([
      {
        title: '设备名称',
        dataIndex: 'devName',
        key: 'devName'
      },
      {
        title: '设备状态',
        dataIndex: 'devStatus',
        key: 'devStatus'
      },
      {
        title: '创建时间',
        dataIndex: 'devCreateTime',
        key: 'devCreateTime'
      },
      {
        title: '最近在线时间',
        dataIndex: 'lastOnlineTime',
        key: 'lastOnlineTime'
      },
      {
        title: '最近离线时间',
        dataIndex: 'lastOfflineTime',
        key: 'lastOfflineTime'
      },
      {
        title: '操作',
        customRender: (row: any) => {
          return (
            <>
              <a-button
                type='primary'
                onClick={() => {
                  toDevInfo(row)
                }}
              >
                {/* <IconImg imgName='edit-content' class='w-24 h-24 mr-12 edit_img '></IconImg> */}
                修改
              </a-button>
              <a-button
                type='primary'
                class='ml-15'
                onClick={() => {
                  tableOperationClick(row)
                }}
              >
                {/* <IconImg imgName='more' class='w-24 h-24 mr-12 edit_img '></IconImg> */}
                更多
              </a-button>
            </>
          )
        }
      }
    ])

    // 搜索条件的数据
    const searchFormData = reactive({
      name: '',
      type: ''
    })

    // 查询的点击事件
    const searchDevClick = () => {
      getPageDataSource()
      console.log(searchFormData)
    }

    // 操作弹窗显示的标识
    const isShowOperationModal = ref(false)

    const handleFinish = () => {}

    const handleFinishFailed = () => {}

    // 存储设备操作列表的数据
    const devOperationList = ref([])

    // 操作弹窗的关闭事件
    const cancelOperationModal = () => {
      console.log('取消')
      isShowOperationModal.value = false
    }

    const operationModalOkClick = () => {
      isShowOperationModal.value = false
      console.log('确定')
    }

    // 当前点击更多按钮的设备信息
    const devInfo = ref({})

    // 表格的更多操作点击事件
    const tableOperationClick = (row: any) => {
      devInfo.value = row
      console.log(row)
      getOperationUtilsFunc(row.value.devId)
      isShowOperationModal.value = true
    }

    // 发送获取更多操作的按钮的请求的函数
    const getOperationUtilsFunc = async (devId: number) => {
      const res = await uSelectDevFunBydDevId({devId: devId})
      devOperationList.value = res.data
      console.log(devOperationList.value)
    }

    watch(
      () => current.value,
      n => {
        console.log(n)

        getPageDataSource()
      }
    )

    return () =>
      route.path === '/deviceManagement/home' ? (
        <div class=''>
          <CnBoldP class='mt-11 text-20'>设备管理</CnBoldP>
          <CnNormalP class='mt-6 mb-8 text-4xText'>
            查看您的设备的总体情况，对需要的设备进行设置
          </CnNormalP>

          <ProductFilesItem></ProductFilesItem>

          <a-spin spinning={state.spinning}>
            <CCard class='min-h-60 bg-white rounded-4 px-0 py-30 px-20 relative' title=''>
              <a-form
                layout='inline'
                v-model={[searchFormData, 'model']}
                finish={handleFinish}
                finishFailed={handleFinishFailed}
              >
                <a-form-item label='设备名称'>
                  <a-input
                    v-model={[searchFormData.name, 'value', ['trim']]}
                    placeholder='请输入设备名称'
                  >
                    {/* <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template> */}
                  </a-input>
                </a-form-item>
                {/* <a-form-item label='设备状态'>
                  <a-input
                    v-model={[searchFormData.type, 'value', ['trim']]}
                    type='text'
                    placeholder='请输入设备名称'
                  >
        
                  </a-input>
                </a-form-item> */}
                <a-form-item>
                  <a-button type='primary' html-type='submit' onClick={searchDevClick}>
                    查询
                  </a-button>
                </a-form-item>
              </a-form>
            </CCard>
            {/* 数据表格 */}
            <CCard class='min-h-100 bg-white rounded-4 px-0 py-16 px-20 relative mt-20' title=''>
              <a-table
                class='dataTable'
                dataSource={devDataTableList.value}
                columns={devDataTableColumns.value}
                pagination={false}
              >
                {/* <slot operation={row}>
                <div>row<div>
                </slot> */}
              </a-table>
              <a-pagination
                style='margin-top:10px'
                v-model={[current.value, 'current']}
                total={total.value}
                size={size.value}
                show-less-items
              />
            </CCard>
          </a-spin>
          <a-modal
            visible={isShowOperationModal.value}
            class='w-500'
            title='设备操作'
            footer={null}
            onOk={() => {
              operationModalOkClick()
            }}
            onCancel={() => {
              cancelOperationModal()
            }}
          >
            <div class='px-24 py-40 h-280 operation_modal_box'>
              {devOperationList.value.map(item => (
                <div class='operatio_item'>
                  <UtilButtonLine value={item} devInfo={devInfo.value}></UtilButtonLine>
                </div>
              ))}
            </div>
          </a-modal>
        </div>
      ) : (
        <RouterView></RouterView>
      )
  }
})

/* 设备数据卡片 */
{
  /* <div class='mt-20 grid grid-cols-3 gap-x-21 gap-y-21'>
              {state.dataSource.map(item => (
                <DeviceCard
                  dev={item}
                  currentDevId={state.currentDev?.devId}
                  onActived={currentDev => {
                    state.currentDev = currentDev
                    getParamsDataByDevId(currentDev.devId)
                  }}
                ></DeviceCard>
              ))}
            </div> */
}

/* 单个设备实时数据展示卡片 */
// {
//   devByCurrentDevId.value ? (
//     <CCard
//       id='deviceManagementParamDashboard'
//       class='min-h-240 bg-white rounded-4 px-0 py-16 relative'
//       title='设备管理-参数面板'
//       vein={true}
//       v-slots={{
//         title: () => (
//           <div class='flex justify-between items-center'>
//             <CnBoldSpan>{`${state.currentDev?.devName || ''}实时参数`}</CnBoldSpan>
//             <CnNormalSpan>{paramDataTime.value}</CnNormalSpan>
//           </div>
//         )
//       }}
//     >
//       <div class='w-full h-full flex justify-around items-center flex-wrap gap-x-26 gap-y-26 mt-20'>
//         {!state.paramListUpdateFlag && state.paramsData.length ? (
//           state.paramsData.map(item => (
//             <div>
//               <CnMediumP class='text-center text-16'>{item.paramName}</CnMediumP>
//               <div class='text-center'>
//                 <ParamValue
//                   value={Number(item.paramValue)}
//                   valueStyle={{
//                     fontSize: '48px'
//                   }}
//                   unit={item.paramUnit}
//                   status={item.paramStatus}
//                 ></ParamValue>
//               </div>
//               <CnNormalP class='text-center'>
//                 {item.standRange ? '合格标准：' + item.standRange : '暂无标准'}
//               </CnNormalP>
//             </div>
//           ))
//         ) : state.paramListUpdateFlag ? (
//           <a-spin spinning={true}></a-spin>
//         ) : !state.paramsData.length ? (
//           '暂无最新记录'
//         ) : null}
//       </div>

//       <div class='absolute bottom-0 right-26 h-26 flex items-center gap-x-16'>
//         <div class='flex items-center gap-x-4'>
//           <div class='w-8 h-8 rounded-full bg-success'></div>
//           <CnNormalSpan>适宜</CnNormalSpan>
//         </div>
//         <div class='flex items-center gap-x-4'>
//           <div class='w-8 h-8 rounded-full  bg-warning'></div>
//           <CnNormalSpan>偏低</CnNormalSpan>
//         </div>
//         <div class='flex items-center gap-x-4'>
//           <div class='w-8 h-8 rounded-full bg-danger'></div>
//           <CnNormalSpan>偏高</CnNormalSpan>
//         </div>
//       </div>
//     </CCard>
//   ) : null
// }
